package com.pb.wkflow.core.listener;

import com.pb.infra.oth.util.SpringContextUtil;
import com.pb.wkflow.core.service.WorkflowMultiService;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.impl.instance.UserTaskImpl;
import org.camunda.bpm.model.bpmn.instance.MultiInstanceLoopCharacteristics;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;

import java.util.Collection;

/**
 * 任务完成时监听器
 * @author 苗益辉
 * @date 2022/5/17 14:50
 */
@Slf4j
public class TaskCompletedListener  implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        WorkflowMultiService workflowMultiService = SpringContextUtil.getBean(WorkflowMultiService.class);
        HistoryService historyService = SpringContextUtil.getBean(HistoryService.class);
        HistoricTaskInstance historicTaskInstance = historyService
                .createHistoricTaskInstanceQuery()
                .taskId(delegateTask.getId())
                .singleResult();
        log.info("当前任务 {}，处理人 {}",historicTaskInstance.getId(), historicTaskInstance.getAssignee());
        BpmnModelInstance bpmnModelInstance = delegateTask.getBpmnModelInstance();
        ModelElementInstance modelElementInstance = bpmnModelInstance.getModelElementById(delegateTask.getTaskDefinitionKey());
        UserTaskImpl userTask = (UserTaskImpl) modelElementInstance;
        Collection<MultiInstanceLoopCharacteristics> mls = userTask.getChildElementsByType(MultiInstanceLoopCharacteristics.class);
        //会签
        if(!mls.isEmpty()) {
            workflowMultiService.dealVotingResult(delegateTask);
        }
    }
}
